package com.fitz.core.filter;

import com.fitz.core.context.FilterConstants;
import com.fitz.core.context.FilterRegistry;
import com.fitz.core.context.RequestContext;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author gousl01
 * @date 2021/3/15 15:30
 * @desc
 */
public class FitzRunner {

    public void init(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse){
        RequestContext requestContext = RequestContext.getCurrentContext();
        requestContext.setRequest(httpServletRequest);
        requestContext.setResponse(httpServletResponse);
    }

    public void preRoute() throws Throwable{
        //找出所有的pre类型的过滤器
        runFilters(FilterConstants.PRE_TYPE);
    }

    public void route()throws Throwable{
        runFilters(FilterConstants.ROUTE_TYPE);
    }

    public void postRoute()throws Throwable{
        runFilters(FilterConstants.POST_TYPE);
    }

    public void errorRoute(){
        runFilters(FilterConstants.ERROR_TYPE);
    }

    private void runFilters(String type){
        List<AbstractFilter> filters = FilterRegistry.getInstance().getFiltersByType(type);
        if (filters != null){
            for (AbstractFilter filter : filters){
                processFilter(filter);
            }
        }
    }

    private void processFilter(AbstractFilter filter){
        filter.runFilter();
    }
}
